/* eslint-disable */
import EventEmitter from 'events';
import { ipcRenderer, ipcMain } from 'electron';

const emitter = new EventEmitter();

const clientInfo = {};
const addEvent = (dom, ev, fn, useCapture = false) => dom.addEventListener(ev, fn, useCapture);
const postMessage = (...data) => {
  // console.log('data ==================> ', data);
  ipcRenderer.sendToHost('pong', ...data);
};

ipcRenderer.on('ping', (e, ...args) => {
  const [cmd, ...data] = args;
  // console.log('ping', ...args);
  switch (cmd) {
    case 'ready':
      Object.assign(clientInfo, data[0] || {}, { isReady: true });
      emitter.emit('ready');
      break;
    default:
      emitter.emit(cmd, ...data);
      break;
  }
});
/**
 *
 */
const exts = {
  get isReady() {
    return clientInfo.isReady;
  },
  get version() {
    return clientInfo.version;
  },
  set dragRegions(val) {
    clientInfo.dragRegions = val;
    postMessage('dragRegions', val);
  },
  get title() {
    return clientInfo.title;
  },
  set title(val) {
    clientInfo.title = val;
    postMessage('title', val);
  },
  set style(val) {
    clientInfo.style = val;
    postMessage('style', val);
  },
  get listenerCount() {
    return emitter.listenerCount;
  },
  removeAllListeners(...args) {
    emitter.removeAllListeners(args);
  },
  on(eventName, listener) {
    emitter.on(eventName, listener);
  },
  once(eventName, listener) {
    emitter.once(eventName, listener);
  },
  off(eventName, listener) {
    emitter.off(eventName, listener);
  },
};

// 无返回值
// createDrawWindows 创建授课工具
// destoryDrawWindows 销毁授课工具
// openTeachingMode 打开授课模式
// openAiPanel 打开Ai面板
// setCourseResource 设置对应的授课资源列表
// teachingQuit 退出授课模式（比如：授课模式种点击其他菜单导致退出了授课）
`setZoomLevel,openDevTools,setAudioMuted,
,print,close,focus,blur,show,showInactive,hide,maximize,unmaximize,minimize,restore,
,setFullScreen,setAlwaysOnTop,center,setProgressBar,setOpacity,setThumbarButtons,setIcon,
,flushStorageData,createInterruptedDownload,setMinimumSize,setMaximumSize,createDrawWindows,destoryDrawWindows,openTeachingMode,openAiPanel,setCourseResource,teachingQuit`
  .split(',')
  .forEach((item) => {
    if (item && item.length > 1) {
      exts[item] = (...args) => {
        // console.log('args =====> ', args);
        postMessage(item, ...args);
      };
    }
  });

const createCid = (item) => {
  return `${new Date().getTime()}${Math.random()}`;
};

// 单返回值
`showItemInFolder,openItem,openPath,trashItem,openExternal,beep,writeShortcutLink,
,getZoomLevel,isAudioMuted,isMaximized,isMinimized,isFullScreen,
,isAlwaysOnTop,getMinimumSize,getOpacity,getMaximumSize,getCacheSize,
,clearCache,clearStorageData,scanSources,scanStart,scanClose,scanFiles,
,scanFile,scanUpload,scanDel,scanDelAll,scanOpenDir,scanQr,scanFileMove,scanFilesEx,scanUploadEx,
,hotCheck,hotUpdate,
,getCfg,download,checkForUpdates,quitAndInstall,bookList,bookInstall,
,bookOpen,bookUninstall,bookDownloadCancel,bookChaptersGet,printToPDF,capturePage`
  .split(',')
  .forEach((item) => {
    if (item && item.length > 1) {
      exts[item] = (...args) => {
        return new Promise(function (resolve, reject) {
          const cmdx = `${item}:${createCid()}`;
          emitter.once(cmdx, (val) => {
            if (val && val.error) {
              reject(val.error);
            } else {
              resolve(val);
            }
          });
          postMessage(cmdx, ...args);
        });
      };
    }
  });

window.exts = exts;
let hasinit;
const init = () => {
  if (hasinit) {
    return;
  }
  document.body.classList.add('client');
  hasinit = true;
};
addEvent(window, 'load', init);
addEvent(document, 'DOMContentLoaded', init);

window.addEventListener('DOMContentLoaded', () => {
  const elements = document.getElementsByTagName('body');
  // 获取坐标
  const listenerCb = (e) => {
    const touch = e.touches[0]; // 获取第一个触点
    const x = touch.clientX; // 获取触点的X坐标
    const y = touch.clientY; // 获取触点的Y坐标
    postMessage('mainWindowsTouch', {
      x,
      y,
    });
  };

  // 点击事件测试触摸
  const listenerCbClick = ({ x, y }) => {
    console.log('e ======> ', { x, y });
    postMessage('mainWindowsTouch', {
      x,
      y,
    });
  };

  Array.from(elements).forEach((el) => {
    console.log('注册移动端点击事件[触摸屏点击]');
    el.addEventListener('touchstart', listenerCb);
    // 测试
    el.addEventListener('click', listenerCbClick);
  });
});
